<template>
  <MainSlot v-loading="loading">
    <template v-slot:searchForm>
      <SearchForm v-if="formItemList.length" :formItemList="formItemList" :unfoldFlag="unfoldFlag" @search="search"
        @isUnfold="(v) => { unfoldFlag = v }">
      </SearchForm>
    </template>

    <template v-slot:tab>
      <EnumSlot @handleEvent="getEnumEvent" :selectIndex="selectIndex" :enumList="enumList"></EnumSlot>
    </template>


    <template v-slot:table>
      <TableData :config="searchFormData.status == 'CREATE' ? table_config : table_config_not_pproved"
        :tableThead="tableThead" :dataList="dataList" :loading="loading" @selection-change="selectionChange">
        <template v-slot:amount="{ row }">{{ row.amount }}{{ row.unitName }}</template>
        <template v-slot:batchName="{ row }">
          <span class="info" v-if="batchObj[row.batchId]">{{ batchObj[row.batchId] }}</span>
          <span v-else>{{ materialRecordableType[row.recordableType] }}不关联批次</span>
        </template>

        <template v-slot:fileIdList="{ row }">
          <el-image v-if="row.imgList && row.imgList.length > 0" class="imageStyle" :src="row.imgList[0]"
            :preview-src-list="row.imgList">
          </el-image>
          <div v-else class="imageStyle noImage">暂无凭证</div>
        </template>

        <template v-slot:recordableType="{ row }">
          <span>{{ materialRecordableType[row.recordableType] }}</span>
        </template>
      </TableData>
      <!-- table_config_not_pproved -->
    </template>

    <template v-slot:pagination>
      <Pagination @size-Change="handleSizeChange" :size="size"   @current-change="handleCurrentChange" :page="page" :total="total">
      </Pagination>
    </template>
  </MainSlot>
</template>

<script>
import MainSlot from "@/components/MainSlot";
import Pagination from '@/components/Pagination';
import SearchForm from '@/components/SearchForm';
import TableData from '@/components/TableData';
import BtnSlot from '@/components/BtnSlot';
import EnumSlot from '@/components/EnumSlot';
import materialInputRecord from '@/api/inputManagment/materialInputRecord.js';
import materialApi from "@/api/basic-info-manage/agr-source-base-Manage"; // 物料
import facilityManagement from '@/api/digtalOperation/facilityManagement.js';
import batch from '@/api/batch/batchManagement';


export default {
  components: { MainSlot, Pagination, SearchForm, TableData, BtnSlot, EnumSlot },
  data() {
    return {
      unfoldFlag: false,
      loading: false,
      dialogVisible: false,
      latLngList: [],
      btnList: ['add', 'delete'],
      formData: {},
      page: 1,
      size:10,
      total: 1000,
      selectIndex: 0,
      dataList: [],
      searchFormData: {
        status: 'CREATE',
      },
      // APPROVAL: "通过"
      // CREATE: "新创建"
      // NOT_APPROVAL: "未通过"
      enumList: [{
        label: "待审核",
        type: 'CREATE'
      },
      {
        label: "审核通过",
        type: 'APPROVAL'
      },
      {
        label: "审核不通过",
        type: 'NOT_APPROVAL'
      }],
      materialRecordableType: {
        DiseaseDeal: "疾病处理",
        EpidemicPrevention: "防疫/消杀",
        FeedWork: "投喂作业",
        Manual: "手动",
      },
      tableThead: [
        { isShow: true, label: '物料名称', prop: 'materialName' },
        { isShow: true, label: '投入数量', slotName: 'amount' },
        { isShow: true, label: '投入鱼塘', prop: 'facilityName' },
        { isShow: true, label: '投入批次', slotName: 'batchName', minWidth: '120px' },
        { isShow: true, label: '物料添加类型', slotName: 'recordableType' },
        { isShow: true, label: '投入日期', prop: 'inputDate' },
        { isShow: true, label: '查看凭证', slotName: 'fileIdList', minWidth: '120px' },
        { isShow: true, label: '操作人', prop: 'staffName' },
        { isShow: true, label: '备注', prop: 'remark' },
      ],
      // 配置项
      table_config: {
        isCheckBox: true,

        isOperation: true,
        // 表格操作列
        operation: {
          label: '操作',
          width: '200',
          cols: [
            {
              label: '通过',
              type: 'primary',
              flag: 'approved',
              handleRow: this.handleRow
            },
            {
              label: '不通过',
              type: 'danger',
              flag: 'notApproved',
              handleRow: this.handleRow
            }
          ]
        },
      },
      table_config_not_pproved: {
        isCheckBox: true,
        isOperation: true,
        // 表格操作列
        operation: {
          label: '操作',
          width: '200',
          cols: [
            {
              label: '删除',
              type: 'danger',
              flag: 'delete',
              handleRow: this.handleRow
            }
          ]
        },
      },
      formItemList: [
        {
          label: '养殖设施',
          type: 'select',
          selectOptions: [],
          param: 'facilityId',
          defaultSelect: '', // 下拉框默认选中项
          multiple: false,
          isShow: true
        },
        {
          label: '养殖批次',
          type: 'select',
          selectOptions: [],
          param: 'batchId',
          defaultSelect: '', // 下拉框默认选中项
          multiple: false,
          isShow: true
        },
        {
          label: '操作人',
          type: 'select',
          selectOptions: [],
          param: 'staffName',
          defaultSelect: '', // 下拉框默认选中项
          multiple: false,
          isShow: true
        }
      ],
      batchList: [],
      batchObj: [],
      facilityList: [],
      materialList: []
    }
  },
  computed: {
    person() {
      return this.$store.state.initData.person || [];
    },
  },
  mounted() {
    this.queryPageByCondition();
    this.initData();
  },
  methods: {
    async initData() {
      let { data: materialList } = await materialApi.getqueryList({});
      this.materialList = materialList;
      // this.materialList = this.materialList.filter(data => {
      //   return data.materialTypeNo == '4165464165465146516' || data.materialTypeNo == '1077222993386450944'
      // })
      // 获取批次列表 
      let { data: batchList } = await batch.queryByCondition({ batchType: 'BREEDING' });
      this.batchList = batchList;
      this.batchObj = {};
      this.batchList.forEach(item => {
        this.batchObj[item.batchId] = item.batchName
      })
      //获取养殖设施；
      let { data: facilityList } = await facilityManagement.getFacilityListByConditionAll({
        breedType: sessionStorage.breedType
      });
      this.facilityList = facilityList || [];
      this.setFormOptions();
    },

    setFormOptions() {
      let list = JSON.parse(JSON.stringify(this.formItemList));
      this.formItemList = []
      list.forEach((item, index) => {
        if (item.param.indexOf('facilityId') !== -1) {
          console.log(this.facilityList)
          let selectOptions = this.facilityList.map(data => {
            return {
              text: data.facilityName, value: data.facilityId
            }
          })
          item.defaultSelect = this.searchFormData[item.param];
          item.selectOptions = selectOptions;
        };
        if (item.param.indexOf('batchId') !== -1) {
          let selectOptions = this.batchList.map(data => {
            return {
              text: data.batchName, value: data.batchId
            }
          })
          item.defaultSelect = this.searchFormData[item.param];
          item.selectOptions = selectOptions;
        };
        if (item.param == 'staffName') {
          let selectOptions = this.person.map(data => {
            return {
              text: data.person.name, value: data.person.name
            }
          })
          item.defaultSelect = this.searchFormData[item.param]
          item.selectOptions = selectOptions;
        };
      });
      this.$nextTick(() => {
        this.$set(this, 'formItemList', list)
        console.log(this.formItemList)
      })
    },
    //获取选中Enum
    getEnumEvent(enumInfo) {
      this.selectIndex = enumInfo.index || 0
      console.log(enumInfo, enumInfo.data.type)
      this.$set(this.searchFormData, 'status', enumInfo.data.type)
      this.queryPageByCondition()
    },
    delList(deleteList = [], key = 'materialRecordId') {
      let list = []
      deleteList.forEach(item => {
        list.push(item[key])
      })
      console.log(list)
      this.$confirm('此操作将永久删除该数据, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        materialInputRecord.delList(list).then(res => {
          if (res.code == 1) {
            this.$message.success(res.msg || '删除成功');
            this.queryPageByCondition();
          } else {
            this.$message.warning(res.msg || '删除失败');
          }
        }).catch(err => {
          this.$message.warning(err.msg || err || '删除失败');
        })

      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    },
    queryPageByCondition() {
      let params = {
        page: this.page,
        size: this.size,
        entity: {
          ...this.searchFormData,
          recordableType: 'Manual'
        }
      }
      // APPROVAL: "通过"
      // CREATE: "新创建"
      // NOT_APPROVAL: "未通过"
      materialInputRecord.queryPageByCondition(params).then(res => {
        if (res.code == 1) {
          this.dataList = res.data.content || [];
          this.dataList.forEach(item => {
            item.imgList = [];
            if (item.fileIdList) {
              let fileIdList = item.fileIdList.split(',')
              fileIdList.forEach(id => {
                item.imgList.push(`${this.$baseurl.fileServiceUrl}fish/public/files/download?fileId=${id}`)
              })
            }
            console.log(item.imgList)
          })
          this.total = res.data.totalElements;
          if (res.data.totalPages && this.page > res.data.totalPages) {
            this.page = res.data.totalPages;
            this.queryPageByCondition();
          }
        } else {
          this.$message.warning(res.msg || '分页查询失败')
        }
      }).catch(err => {
        console.log(err)
      })
    },
    search(data) {
      this.page = 1;
      this.searchFormData ={...this.searchFormData,...data };
      this.queryPageByCondition();
    },
    handleCurrentChange(page) {
      this.page = page;
      this.queryPageByCondition();
    },
    handleSizeChange(size) {
      this.size = size;
      this.queryPageByCondition();
    },
    // 操作方法
    handleRow(rowData, item) {
      if (item.flag == 'approved') {
        this.approved(rowData.materialRecordId, true)
      } else if (item.flag == 'notApproved') {
        this.approved(rowData.materialRecordId, false)
      } else if (item.flag == 'delete') {
        this.delList([rowData]);
      }
    },
    //flag true通过  false不通过
    approved(id, flag) {
      let text = flag ? '通过' : '不通过'
      let api = flag ? materialInputRecord.approved : materialInputRecord.notApproved
      this.$confirm(`您确定要${text}该数据？`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        api(id).then(res => {
          if (res.code == 1) {
            this.$message.success(res.msg || '操作成功');
            this.queryPageByCondition();
          } else {
            this.$message.warning(res.msg || '操作失败');
          }
        }).catch(err => {
          console.log(err)
        })

      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消'
        });
      });
    },
    // 多选方法
    selectionChange(val) {
      this.selectList = val || []
    },
    //关闭弹窗
    closeDialog() {
      this.dialogVisible = false;
      this.queryPageByCondition();
    },
  }
};
</script>

<style lang="scss" scoped>
.pointer {
  cursor: pointer;
}

.info {
  color: rgb(17, 107, 180);
}

.imageStyle {
  width: 80px;
  height: 80px;
  line-height: 80px;
  text-align: center;
  margin: 0 auto;
}

.noImage {
  background-color: rgb(247, 247, 247);
  border: 1px solid #e6e6e6;
  border-radius: 4px;
  color: #999999;
}
</style>